package com.gamex.findit.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class CryptoUtil {
	public final static String UTF_8 = "UTF-8";
	public final static String SHA_1 = "SHA-1";
	public final static String DESEDE = "DESede";
	public final static String DESEDE_CBC_PKCS5PADDING = "DESede/CBC/PKCS5Padding";
	public final static String DESEDE_ECB_PKCS5PADDING = "DESede/ECB/PKCS5Padding";
	
	private static IvParameterSpec spec = new IvParameterSpec(new byte[8]);
	private static SecretKeySpec getSecretKeySpec(String username) throws Exception {
		String key = Generator.getBase64EncodedHash(SHA_1, username);
		byte[] keyBytes = key.substring(0, 24).getBytes();
		return new SecretKeySpec(keyBytes, DESEDE);
	}
	
	/** 신규 쓰지마셈 */
	public static String encryptSSN(String idn, String username) throws Exception {
		if (idn == null) return null;

		SecretKeySpec secreteKey = getSecretKeySpec(username);
		Cipher cipher = Cipher.getInstance(DESEDE_CBC_PKCS5PADDING);
		cipher.init(Cipher.ENCRYPT_MODE, secreteKey, spec);
		byte[] encrypted = cipher.doFinal(idn.getBytes());
		return Base64.encodeBase64String(encrypted);
	}

	/** 신규 쓰지마셈 */
	public static String decryptSSN(String encryptedIDN, String username) throws Exception {
		if (encryptedIDN == null) return null;

		SecretKeySpec secreteKey = getSecretKeySpec(username);
		Cipher cipher = Cipher.getInstance(DESEDE_CBC_PKCS5PADDING);
		cipher.init(Cipher.DECRYPT_MODE, secreteKey, spec);
		byte[] enc = Base64.decodeBase64(encryptedIDN);
		byte[] decryptedString = cipher.doFinal(enc);
		return new String(decryptedString, UTF_8);
	}

	/** 기존 호환 */
	public static String encryptIDN(String idn, String username) throws Exception {
		if (idn == null) return null;

		SecretKeySpec secreteKey = getSecretKeySpec(username);

		Cipher cipher = Cipher.getInstance(DESEDE_ECB_PKCS5PADDING);
		cipher.init(Cipher.ENCRYPT_MODE, secreteKey);

		byte[] encrypted = cipher.doFinal(idn.getBytes());
		return Base64.encodeBase64String(encrypted);
	}

	/** 기존 호환 */
	public static String decryptIDN(String encryptedIDN, String username) throws Exception {
		if (encryptedIDN == null) return null;

		SecretKeySpec secreteKey = getSecretKeySpec(username);
		Cipher cipher = Cipher.getInstance(DESEDE_ECB_PKCS5PADDING);
		cipher.init(Cipher.DECRYPT_MODE, secreteKey);
		byte[] enc = Base64.decodeBase64(encryptedIDN);
		byte[] decryptedString = cipher.doFinal(enc);
		return new String(decryptedString, UTF_8);
	}
	
	public static String getEncryptedPassword(String password) {
		try {
			return Generator.getBase64EncodedHash(SHA_1, password);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
}
